import React, { useState, useEffect, useRef } from 'react';
import { Input, Button, List, message, Card, Space } from 'antd';
import { SendOutlined, LinkOutlined, DisconnectOutlined } from '@ant-design/icons';
import './App.css';

function App() {
  // 状态管理
  const [messages, setMessages] = useState([]); // 消息列表
  const [inputValue, setInputValue] = useState(''); // 输入框内容
  const [connected, setConnected] = useState(false); // 连接状态
  const [loading, setLoading] = useState(false); // 加载状态

  // WebSocket引用
  const ws = useRef(null);

  // 连接WebSocket
  const connectWebSocket = () => {
    setLoading(true);

    // 创建WebSocket连接
    ws.current = new WebSocket('ws://localhost:8000/ws');

    // 连接成功回调
    ws.current.onopen = () => {
      setConnected(true);
      setLoading(false);
      message.success('已连接到WebSocket服务器');
    };

    // 接收消息回调
    ws.current.onmessage = (e) => {
      const data = JSON.parse(e.data);
      setMessages(prev => [...prev, {
        time: data.time,
        author: data.client,
        content: data.content
      }]);
    };

    // 连接关闭回调
    ws.current.onclose = () => {
      setConnected(false);
      message.warning('已断开WebSocket连接');
    };

    // 错误处理
    ws.current.onerror = (err) => {
      console.error('WebSocket错误:', err);
      message.error('WebSocket连接错误');
      setLoading(false);
    };
  };

  // 断开WebSocket连接
  const disconnectWebSocket = () => {
    if (ws.current) {
      ws.current.close();
    }
  };

  // 发送消息
  const sendMessage = () => {
    if (!connected) {
      message.warning('请先连接WebSocket');
      return;
    }

    if (!inputValue.trim()) {
      message.warning({
        "type": "text",
        "data": {
          "content": "这是一条文本消息",
          "name": "zhangsan"
        }
      });
      return;
    }

    ws.current.send(JSON.stringify(
      {
        "type": "text",
        "data": {
          "content": inputValue,
          "name": "zhangsan"
        }
      }
    )
    );
    setInputValue('');
  };

  // 组件卸载时断开连接
  useEffect(() => {
    return () => {
      if (ws.current) {
        ws.current.close();
      }
    };
  }, []);

  return (
    <div className="app-container">
      <Card
        title="WebSocket聊天室"
        variant={false}
        extra={
          <Space>
            {!connected ? (
              <Button
                type="primary"
                icon={<LinkOutlined />}
                onClick={connectWebSocket}
                loading={loading}
              >
                连接
              </Button>
            ) : (
              <Button
                danger
                icon={<DisconnectOutlined />}
                onClick={disconnectWebSocket}
              >
                断开
              </Button>
            )}
          </Space>
        }
      >
        <div className="chat-container">
          {/* 消息列表 */}
          <List
            className="message-list"
            itemLayout="horizontal"
            dataSource={messages}
            renderItem={item => (
              <List.Item>
                <List.Item.Meta
                  title={`${item.author} - ${item.time}`}
                  description={item.content}
                />
              </List.Item>
            )}
          />

          {/* 输入区域 */}
          <div className="input-area">
            <Input
              value={inputValue}
              onChange={e => setInputValue(e.target.value)}
              onPressEnter={sendMessage}
              placeholder="输入消息..."
              disabled={!connected}
            />
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={sendMessage}
              disabled={!connected}
            >
              发送
            </Button>
          </div>
        </div>
      </Card>
    </div>
  );
}

export default App;